package com.edu.controller;

import com.edu.entity.CommonResult;
import com.edu.entity.Good;
import com.edu.entity.User;
import com.edu.feign.GoodServiceProviderService;
import com.edu.feign.UserServiceProviderService;
import com.edu.service.UserService;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.CompletableFuture;


@RestController
@RequestMapping("/cart")
@LoadBalancerClient(name = "user-provider-service")
public class CartController {
    //   注入Fegin接口（@EnableFeignClients自动扫描@FeignClient注解）
    @Autowired
    private UserServiceProviderService userServiceProviderService;
    @Autowired
    private GoodServiceProviderService goodServiceProviderService;
    @Autowired
    private UserService userService;

    // 测试缓存
    @GetMapping("/getUserById/{userId}")
    public CommonResult<User> getUserById(@PathVariable("userId") Integer userId) {
        return new CommonResult(200, "success", userService.getUserById(userId));
    }
//    @GetMapping("/getUserById/{userId}")
//    @TimeLimiter(name = "time1", fallbackMethod = "getUserByIdDown")
//    public CompletableFuture<User> getUserById(@PathVariable("userId") Integer userId) {
//        String message = "该功能当前正常！";
//        System.out.println(message);
//        return CompletableFuture.completedFuture(userServiceProviderService.getUserById(userId).getResult());
//    }
//
//    public CompletableFuture<User> getUserByIdDown(Integer userId, Throwable e) {
//        e.printStackTrace();
//        String message = "该功能当前异常火爆，请稍候再试！(超时控制)";
//        System.out.println(message);
//        return CompletableFuture.completedFuture(new CommonResult<>(400, message, new User()).getResult());
//    }

//    @GetMapping("/getUserById/{userId}")
//    @RateLimiter(name = "rate1", fallbackMethod = "getUserByIdDown")
//    public CommonResult<User> getUserById(@PathVariable("userId") Integer userId) {
//        CommonResult<User> result = userServiceProviderService.getUserById(userId);
//        return result;
//    }
//
//    public CommonResult<User> getUserByIdDown(Integer userId, Throwable e) {
//        e.printStackTrace();
//        String message = "该功能当前异常火爆，请稍候再试";
//
//        CommonResult<User> result = new CommonResult<>(400, message, new User());
//        return result;
//    }

//    @GetMapping("/getUserById/{userId}")
//    @Bulkhead(name = "bulkend1", fallbackMethod = "getUserByIdDown", type = Bulkhead.Type.SEMAPHORE)
//    public CompletableFuture<User> getUserById(@PathVariable("userId") Integer userId) {
//        CompletableFuture<User> result = CompletableFuture.supplyAsync(() -> {
//            return userServiceProviderService.getUserById(userId).getResult();
//        });
//        String message = "该功能当前正常！";
//        System.out.println(message);
//        return result;
//    }
//
//    public CompletableFuture<User> getUserByIdDown(@PathVariable("userId") Integer userId, Throwable e) {
//        e.printStackTrace();
//        String message = "该功能当前异常火爆，请稍候再试！";
//        System.out.println(message);
//        return CompletableFuture.supplyAsync(() -> {
//            return new CommonResult<>(400, "fallback", new User()).getResult();
//        });
//    }

    @GetMapping("/getUserByName/{userName}")
    @CircuitBreaker(name = "backendA", fallbackMethod = "getUserByNameDown")
    public CommonResult getUserByName(@PathVariable("userName") String userName) {
        //使用Fegin接口进行服务调用
        return userServiceProviderService.getUserByName(userName);
    }

    public CommonResult getUserByNameDown(@PathVariable("userName") String userName, Throwable e) {
        e.printStackTrace();
        String message = "获取用户" + userName + "信息的服务当前被熔断，因此方法被降级,使用断路器实例B";
        System.out.println(message);
        return new CommonResult<>(400, message, new User());
    }


    @PostMapping("/addGood")
    public CommonResult addGood(@RequestBody Good good) {
        return goodServiceProviderService.addGood(good);
    }

    @PutMapping("/updateGood")
    public CommonResult updateGood(@RequestBody Good good) {
        try {
            return goodServiceProviderService.updateGood(good);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "修改商品失败", null);
        }
    }


    @DeleteMapping("/deleteGoodById/{goodId}")
    public CommonResult deleteGood(@PathVariable("goodId") Integer goodId) {
        try {
            return goodServiceProviderService.deleteGoodById(goodId);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "删除商品失败", null);
        }

    }


}


